<script setup lang="ts">
import {ref} from 'vue'
import { useStore } from 'vuex';
import axios from "axios";

const store = useStore();
const fileInput = ref(null);

function handleFileUpload(event: Event) {
  const file = event.target.files[0];
  store.commit("setDetectFlag",false)
  store.commit("setDetectUrl",[])
  console.log(file)
  if (file) {
    const fileType = file.type;
    if (fileType.startsWith('image/')) {
      // 文件是图片，进行压缩
      compressImage(file, (compressedFile) => {
        store.commit("setFileUrl", [URL.createObjectURL(compressedFile), 'image']);
      });
      store.commit("setFileUrl",[URL.createObjectURL(file), 'image']);

    } else if (fileType.startsWith('video/')) {
      // 文件是视频
      store.commit("setFileUrl", [URL.createObjectURL(file), 'video']);
    }
  }
}

function compressImage(file: File, callback: (compressedFile: File) => void) {
  const reader = new FileReader();
  reader.onload = (event) => {
    const image = new Image();
    image.src = event.target.result as string;
    image.onload = () => {
      const canvas = document.createElement('canvas');
      const maxWidth = 700; // 设置最大宽度
      const maxHeight = 500; // 设置最大高度
      let width = image.width;
      let height = image.height;

      if (width > maxWidth) {
        height *= maxWidth / width;
        width = maxWidth;
      }

      if (height > maxHeight) {
        width *= maxHeight / height;
        height = maxHeight;
      }

      canvas.width = width;
      canvas.height = height;

      const ctx = canvas.getContext('2d');
      ctx.drawImage(image, 0, 0, width, height);

      canvas.toBlob((blob) => {
        const compressedFile = new File([blob], file.name, {
          type: file.type,
          lastModified: Date.now(),
        });

        callback(compressedFile);
      }, file.type);
    };
  };
  reader.readAsDataURL(file);
}
async function uploadFile() {
  console.log("上传!!!")
  const file = fileInput.value.files[0];
  store.commit("setDetectFlag",true);
  const startTime = performance.now(); // 获取开始时间
  if (file) {
    // console.log("!!!",file);
    const formData = new FormData();
    formData.append('source', file);

    try {

      const response = await axios.post('http://localhost:8080/yolo/detect', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      // console.log(1111);
      const endTime = performance.now(); // 获取结束时间

      // 结束计时并打印执行时间（以秒为单位）
      const executionTimeInSeconds = (endTime - startTime) / 1000;
      console.log('File uploaded successfully in', executionTimeInSeconds, 'seconds');
      console.log('File uploaded successfully', response.data);
      store.commit("setDetectUrl",response.data)
    } catch (error) {
      console.error('File upload failed', error);
    }
  }
}
</script>

<template>
  <div class="File">
    <form >
      <input type="file" ref="fileInput" accept="image/*,video/*" @change="handleFileUpload" />
    </form>
    <el-button @click="uploadFile">检测</el-button>
  </div>
</template>

<style scoped lang="scss">
  .File{
    width: 100%;
    height: 50px;
    background-color: #213547;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>

